package si.yun.web.handler;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import si.yun.web.UserDetailController;

import javax.sql.DataSource;

/**
 * @ClassName: Security配置类
 * @Description: TODO
 * @Author: 李振海
 * @Date 2021/9/29 19:26
 */
@Configuration

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAccessDeniedHandler accessDeniedHandler;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    @Autowired
    private UserDetailController userDetailServiceImpl;
    /*
    * 相当于将BCryptPasswordEncoder交给spring管理
    * */
    @Bean
    public PasswordEncoder getPw(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //表单提交
        http.formLogin()
                //自定义入参
                .usernameParameter("name")
                .passwordParameter("pwd")
                //自定义登陆页面
                .loginPage("/login/SyLogin.html")
                //必须和表单提交得接口一样，会去执行自定义登录逻辑
                .loginProcessingUrl("/login")
                //自定义登陆成功处理器
                //.successHandler( new MyAuthenticationSuccessHandler("/public/index.html"))
                //登陆成功后跳转的页面，只接受post请求
                .successForwardUrl("/login/index")
                //登陆失败后跳转的页面，只接受post请求
                .failureForwardUrl("/login/toError");


        //http.sessionManagement() .sessionFixation().migrateSession();


        //授权
        http.authorizeRequests()
                //放行/login/SyLogin.html,不需要认证
                .antMatchers("/login/SyLogin.html").permitAll()
                .antMatchers("/login/css/**").permitAll()
                .antMatchers("/login/js/**").permitAll()
                .antMatchers("/layui/**").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/public/index/**").permitAll()
                .antMatchers("/img/**").permitAll()
                .antMatchers("/getImg").permitAll()
                .antMatchers("/getCode").permitAll()
                .antMatchers("/getEnabled").permitAll()
				.antMatchers("/login/Forget.html").permitAll()
                .antMatchers("/account/getAccount").permitAll()
                .antMatchers("/login/Forget_phone.html").permitAll()
                .antMatchers("/account/getPhoneNumber").permitAll()
                .antMatchers("/account/getValidation").permitAll()
                .antMatchers("/login/Forget_setPwd.html").permitAll()
                .antMatchers("/account/getPassword").permitAll()
                .antMatchers("/account/setPwd").permitAll()


                //放行/login/error.html,不需要认证,放行异常页面
                //.antMatchers("/login/error.html").permitAll()
                .antMatchers("/public/index/error.html").access("permitAll")
                .antMatchers("/11.html").hasAnyAuthority("root","root1")

                //所有请求都需要认证（都需要登录）,必须放在最后，与拦截器相同差不多
                .anyRequest().authenticated();


        //异常处理
        http.exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler);


        //退出登录
        http.logout()
                //自定义退出路径 没必要
               // .logoutUrl("/login/SyLogin")
                //退出成功后跳转得页面
                .logoutSuccessUrl("/login/SyLogin.html");

        //关闭csrf防护
        http.csrf().disable();

        //页面内跳转
        http.headers().frameOptions().sameOrigin();

        http.sessionManagement()
                // session超时跳转
                .invalidSessionUrl("/login/SyLogin.html");


    }



    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository=new JdbcTokenRepositoryImpl();
        //设置数据源
        jdbcTokenRepository.setDataSource(dataSource);
        //自动建表，第一次启动时开启，第二次启动时注释掉
       // jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }






}
